<template>
  <view class="login-page">
    <view class="app-content">
      <header class="app-header">
        <view class="app-logo"></view>
        <!-- [修改] 更新品牌名称 -->
        <h1 class="app-title">欢迎来到四谷家政</h1>
      </header>

      <main class="login-container">
        <view class="tabs">
          <view class="tab-item" :class="{ active: activeTab === 'account' }" @click="switchTab('account')">账号密码登录</view>
          <view class="tab-item" :class="{ active: activeTab === 'phone' }" @click="switchTab('phone')">手机号登录</view>
        </view>

        <!-- 账号密码登录表单 -->
        <view v-if="activeTab === 'account'" class="form-panel active">
          <view class="input-group">
            <input class="input-field" type="text" v-model="accountForm.username" placeholder="请输入用户名/手机号" />
          </view>
          <!-- [修改] 增加密码输入框和眼睛图标 -->
          <view class="input-group">
            <input class="input-field" :type="passwordFieldType" v-model="accountForm.password" placeholder="请输入密码" />
            <image 
              class="password-toggle"
              :src="passwordFieldType === 'password' ? '/static/icons/eye-slash.svg' : '/static/icons/eye-open.svg'"
              @click="togglePasswordVisibility"
            ></image>
          </view>
          <view class="extra-links">
            <text></text>
            <text class="link" @click="handleForgetPassword">忘记密码?</text>
          </view>
          <button class="main-btn" @click="handleLogin">登 录</button>
        </view>

        <!-- 手机号验证码登录表单 -->
        <view v-if="activeTab === 'phone'" class="form-panel active">
          <view class="input-group">
            <input class="input-field" type="number" v-model="phoneForm.phone" placeholder="请输入手机号" />
          </view>
          <view class="input-group">
            <input class="input-field" type="number" v-model="phoneForm.code" placeholder="请输入验证码" />
            <button class="get-code-btn" :class="{ counting: isCounting }" @click="getCode" :disabled="isCounting">
              {{ countdownText }}
            </button>
          </view>
          <button class="main-btn" @click="handleLogin">登 录 / 注 册</button>
        </view>
      </main>

      <footer class="register-info">
        <text>还没有账号? </text>
        <text class="link" @click="gotoRegister">立即注册</text>
      </footer>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { onReady } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';

// 数据模型
const activeTab = ref('account'); // 'account' 或 'phone'
const passwordFieldType = ref('password'); // [新增] 密码框类型

// 账号密码登录表单数据
const accountForm = reactive({
  username: '',
  password: '',
});

// 手机号登录表单数据
const phoneForm = reactive({
  phone: '',
  code: '',
});

// 验证码倒计时
const countdown = ref(60);
const isCounting = ref(false);
let timer = null;

const countdownText = computed(() => {
  return isCounting.value ? `${countdown.value}秒后重试` : '获取验证码';
});

// 方法
const switchTab = (tab) => {
  activeTab.value = tab;
};

// [新增] 密码可见性切换
const togglePasswordVisibility = () => {
  passwordFieldType.value = passwordFieldType.value === 'password' ? 'text' : 'password';
};

const getCode = async() => {
  if (isCounting.value) return;
	if (!phoneForm.phone) {
		uni.showToast({
			title: '请输入手机号', icon:'none'
		});
		return;
	}
	
	try {
		codeData = await request({
			url: '/user/sendCode',
			method: 'POST',
			data: {
				userPhone: phoneForm.phone
			}
		});
		// console.log('验证码发送成功，返回数据:', codeData);
		uni.showToast({
			title: '验证码已发送', icon: 'success'
		});
		
		timer = setInterval(() => {
			countdown.value--;
			if (countdown.value <= 0) {
				clearInterval(timer);
				isCounting.value = false;
				countdown.value = 4;
			}
		}, 1000);
	} catch (error) {
		console.error('发送验证码失败:', error);
	}
};

const handleLogin = async() => {
	let params = {};
	let url = '/login';
	
  if (activeTab.value === 'account') {
		if (!accountForm.username || !accountForm.password) {
			uni.showToast({
				title: '请输入账号和密码', icon:'none'
			});
			return;
		}
		params = {
			accountUsername: accountForm.username,
			accountPassword: accountForm.password
		};
  } else {
		url = '/user/loginduanxin';
		if (!phoneForm.phone || !phoneForm.code) {
			uni.showToast({
				title: '请输入手机号和验证码', icon: 'none'
			});
			return;
		}
		params = {
			phone: phoneForm.phone,
			code: phoneForm.code
		};
  }
	try {
		const loginData = await request({
			url: url,
			method: 'POST',
			data: params
		});
		console.log('登陆成功，返回数据:', loginData);
		
		if (loginData.accountRole == "1") {
			uni.setStorageSync('userInfo', loginData);
			uni.setStorageSync('userId', loginData.userId);
			
			uni.showToast({
				title: '登陆成功!', icon:'success'
			});
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 1500);
		} else {
			uni.showToast({
				title: '非用户账号，登陆失败!', icon:'none'
			});
			return;
		}
	} catch (error) {
		console.error('登录失败:',error);
	}
};

const handleForgetPassword = () => {
  uni.showToast({ title: '功能开发中', icon: 'none' });
};

const gotoRegister = () => {
  uni.navigateTo({ url: '/pages/login/register' });
};
</script>

<style lang="scss" scoped>
.login-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $uni-bg-color-white;
}
.app-content {
  padding: 80rpx 60rpx;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}
.app-header {
  text-align: center;
  margin-bottom: 80rpx;
}
.app-logo {
  width: 140rpx;
  height: 140rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent);
  border-radius: 36rpx;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 8rpx 20rpx rgba(74, 144, 226, 0.3);
  // 这里可以放你们的logo
  background-image: url("/static/logo.png"); 
  background-size: 60%;
  background-repeat: no-repeat;
  background-position: center;
}
.app-title {
  font-size: 52rpx;
  font-weight: 500;
  margin-top: 30rpx;
}
.login-container {
  flex-grow: 1;
}
.tabs {
  display: flex;
  margin-bottom: 60rpx;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 36rpx;
  font-weight: 500;
  color: $uni-text-color-light;
  position: relative;
  transition: color 0.3s ease;
  &.active {
    color: $uni-primary;
    &::after {
      content: '';
      position: absolute;
      bottom: -4rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 40%;
      height: 6rpx;
      background-color: $uni-primary;
      border-radius: 4rpx;
    }
  }
}
.form-panel.active {
  animation: fadeIn 0.5s ease;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}
.input-group {
  position: relative;
  margin-bottom: 40rpx;
  border-bottom: 1px solid $uni-border-color;
  transition: border-color 0.3s;
  &:focus-within { // 当内部元素获得焦点时
    border-color: $uni-primary;
  }
}
.input-field {
  width: 100%;
  padding: 30rpx 0;
  border: none; // 边框移到父级
  font-size: 32rpx;
  
}
.password-toggle {
  position: absolute;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 40rpx;
  height: 40rpx;
}
.extra-links {
  display: flex;
  justify-content: space-between;
  margin-top: -20rpx; // 向上移动一点
  margin-bottom: 40rpx;
  font-size: 28rpx;
}
.link {
  color: $uni-text-color-light;
  &:hover {
    color: $uni-primary;
  }
}
.get-code-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background-color: transparent;
  color: $uni-primary;
  border: none;
  padding: 20rpx;
  font-size: 28rpx;
  font-weight: 500;
  border-radius: 16rpx;
  &::after { border: none; }
  &.counting { color: $uni-text-color-light; }
}
.main-btn {
  width: 100%;
  padding: 28rpx;
  margin-top: 40rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent);
  color: white;
  border: none;
  border-radius: 24rpx;
  font-size: 36rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 30rpx rgba(74, 144, 226, 0.3);
}
.register-info {
  margin-top: auto;
  padding-top: 40rpx;
  text-align: center;
  font-size: 28rpx;
  color: $uni-text-color-light;
  .link {
    color: $uni-primary;
    font-weight: 500;
  }
}
</style>